#include <malloc.h>
#include <string.h>
#include "HoFile.h"

BOOL file_exist(char *filename) {
	FILE *file = fopen(filename, "r");
	if (file == NULL) {
		return FALSE;
	} else {
		close_file(file);
		return TRUE;
	}
}

char read_byte(FILE *file) {
    char *c = (char*)malloc(sizeof(char) * 1);
    memset(c, 0, sizeof(char) * 1);
    size_t read_size = fread(c, 1, 1, file);
    if (read_size > 0) {
        return *c;
    }
    return (char)0;
}

char* read_line(FILE *file) {
    int current_length = 5;
    int current_index = 0;
    char *s = (char*)malloc(sizeof(char) * current_length);
    char *c = (char*)malloc(sizeof(char) * 1);
    memset(s, 0, sizeof(char) * current_length);
    memset(c, 0, sizeof(char) * 1);
    while (!feof(file)) {
        ++current_index;
        size_t read_size = fread(c, 1, 1, file);
        if (read_size > 0) {
            if (*c != '\n') {
                strcat(s, c);
                if (current_index % 5 == 0) {
                    current_length += 5;
                    s = (char*)realloc(s, sizeof(char) * current_length);
                }
            } else {
                break;
            }
        }
    }
    free(c);
    return s;
}

char* read_byline(FILE* file, int line_number) {
    int len = 0, _line1 = line_number, _line2 = line_number;
	char *c = (char*)malloc(sizeof(char) * 1);
	if (c == NULL) {
		return "";
    }
	memset(c, 0, sizeof(char) * 1);
    fseek(file, 0L, SEEK_SET);
	while (!feof(file)) {
        fread(c, 1, 1, file);
        if (*c == '\n' && _line1 > 1) {
            --_line1;
            continue;
        } else if (*c != '\n' && _line1 == 1) {
            ++len;
        } else if (*c == '\n' && _line1 == 1) {
            break;
        }
	}
    char* s = (char*)malloc(sizeof(char) * (len + 1));
	if (s != NULL) {
        memset(s, 0, sizeof(char) * (len + 1));
        if (fseek(file, 0L, SEEK_SET) == 0) {
			while (!feof(file)) {
                size_t read_size = fread(c, 1, 1, file);
				if (read_size > 0) {
                    if (*c == '\n' && _line2 > 1) {
                        --_line2;
                        continue;
                    } else if (*c != '\n' && _line2 == 1) {
                        strcat(s, c);
                    } else if (*c == '\n' && _line1 == 1) {
                        break;
                    }
				}
			}
		}
	}
	return s;
}

void write_string(FILE *file, char *str) {
    char *temp = str;
    int len = 0;
    while (*temp) {
        ++len;
        ++temp;
    }
    fwrite(str, len, 1, file);
    fflush(file);
}

void close_file(FILE* file) {
	if (file != NULL) {
		fclose(file);
		file = NULL;
	}
}
